import { createPinia, defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'

// 新闻数据存储
export const useNewsStore = defineStore('news', () => {
  const news = ref([])
  const categories = ref(['头条', '科技', '体育', '娱乐', '财经'])
  const currentCategory = ref('头条')
  const searchHistory = ref(JSON.parse(localStorage.getItem('searchHistory') || '[]'))

  const setNews = (data) => { news.value = data }
  const setCurrentCategory = (category) => { currentCategory.value = category }
  const addSearchHistory = (keyword) => {
    if (!searchHistory.value.includes(keyword)) {
      searchHistory.value.unshift(keyword)
      if (searchHistory.value.length > 10) searchHistory.value.pop()
      localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
    }
  }

  return { news, categories, currentCategory, searchHistory, setNews, setCurrentCategory, addSearchHistory }
})

// 收藏存储
export const useFavoritesStore = defineStore('favorites', () => {
  const favorites = ref(JSON.parse(localStorage.getItem('newsFavorites') || '[]'))

  const isFavorite = computed(() => (id) => favorites.value.some(item => item.id === id))

  const toggleFavorite = (newsItem) => {
    const index = favorites.value.findIndex(item => item.id === newsItem.id)
    if (index === -1) {
      favorites.value.push(newsItem)
    } else {
      favorites.value.splice(index, 1)
    }
    localStorage.setItem('newsFavorites', JSON.stringify(favorites.value))
  }

  watch(favorites, (newValue) => {
    localStorage.setItem('newsFavorites', JSON.stringify(newValue))
  }, { deep: true })

  return { favorites, isFavorite, toggleFavorite }
})

export default createPinia()